package com.flute.icrawler.check.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


public class SerializeId {
	
	File file = null;
	String pathfile = "path.file";
	String ratefile = "rate.file";
	String dir = Util.getRootDir("") + ratefile;
	
	static SerializeId serializeId;
	
	public static SerializeId getInstance(){
		if(serializeId == null){
			serializeId = new SerializeId();
		}
		return serializeId;
	}
	
	SerializeId(){
		checkFileisExists(this.file);
	}
	
	public void checkFileisExists(File file){
		 if(file == null){
			 File newfile = new File(dir);
				if(!newfile.exists()){
					try {
						newfile.createNewFile();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				 this.file = newfile;
		 }else{
			 this.file = file;
		 }
	}
	/**
	 * 序列化保存对象
	 * @param obj
	 */
	public  void saveSerializeObj(Object obj){
		
		try {
			// 1.创建文件输出流,负责将字节写入文件
			FileOutputStream fs = new FileOutputStream(this.file);
			// 2.创建对象输出流,负责将对象转为字节
			ObjectOutputStream os = new ObjectOutputStream(fs);
			// 3.写入对象
			os.writeObject(obj);
			// 4.关闭对象输出流
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 解序列化
	 * @return
	 */
	public  Object uncoilSerializeObj(){
		Object obj = null;
		try {
			if(this.file.length()<=0){
				return null;
			}
			// 1.创建文件输入流,负责将文件转为字节
			FileInputStream fi = new FileInputStream(this.file);
			
			// 2.创建对象输入流,负责将字节写入对象
			ObjectInputStream oi = new ObjectInputStream(fi);
			// 3.读出对象
			obj = oi.readObject();
			// 4.关闭对象输入流
			oi.close();
		}  catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}

}
